function res = coxRegress(X,Y,censorvec,nFolds)


%%%%%
% This function performs Cox regression on survival data.
%
% Inputs:
% X - input data matrix, rows are subjects and columns are covariates.
% Y - column vector containing survival time, should correspond to the rows in X.
% censorvec - boolean column vector indicating right-censored data; 0 = not censored, 1 = right-censored. Should correspond to the elements in Y.
% nFolds - number of folds in cross-validation
%
% Outputs:
% res - structure containing Cox regression results.
%
% Written by Joon Lee, 2011
%%%%%


res.N=size(X,1);
[res.b,res.logl,res.H,res.stats]=coxphfit(X,Y,'censoring',censorvec);
res.C=coxC(X,Y,censorvec);
res.goodness_of_fit_p=coxgof(X,Y,censorvec);

% cross-validation    
randidx=randperm(res.N);
Xrand=X(randidx,:);
Yrand=Y(randidx);
temp=[];
C=0;
Q=0; 

for k=0:nFolds-1
    testIdx=mod(1:res.N,nFolds)==k;
    trainIdx=~testIdx;
    [b,logl,H]=coxphfit(Xrand(trainIdx,:),Yrand(trainIdx),'censoring',censorvec(trainIdx),'baseline',0);    
    risk=exp(Xrand(testIdx,:)*b);
    prob=1-exp(-H(end,2)).^risk;    
    survivalTime=Yrand(testIdx);
    censorvecTest=censorvec(testIdx);
    n=length(prob);
    %C=0;
    %Q=0;
    for i=1:n-1
        for j=i+1:n            
            if ~censorvecTest(i) && ~censorvecTest(j)
                Q=Q+1;
                if (survivalTime(i)<survivalTime(j) && prob(i)>prob(j)) || (survivalTime(i)>survivalTime(j) && prob(i)<prob(j))
                    C=C+1;
                end
            elseif ~censorvecTest(i) && censorvecTest(j) && survivalTime(i)<survivalTime(j)
                Q=Q+1;
                if prob(i)>prob(j)
                    C=C+1;
                end
            elseif censorvecTest(i) && ~censorvecTest(j) && survivalTime(i)>survivalTime(j)
                Q=Q+1;
                if prob(i)<prob(j)
                    C=C+1;
                end
            end            
        end
    end    
    %C=C/Q;
    %temp=[temp C];
end

res.xvalvec=temp;
res.xval=[C/Q 0];
